package com.jessechanrui.template.common.template.auth.common;

import com.jessechanrui.template.common.template.auth.application.dto.UserDTO;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.authcenter.AuthCenterTenant;
import jakarta.servlet.http.HttpServletRequest;


public class AuthorizationSupport {

    // 用户token
    private static final ThreadLocal<String> USER_TOKEN = new ThreadLocal<>();
    private static final ThreadLocal<UserDTO> USER_INFO = new ThreadLocal<>();
    private static final ThreadLocal<String> TENANT_ID = new ThreadLocal<>();

    public static String getTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null) {
            if (token.startsWith("Bearer")) {
                token = token.replace("Bearer ", "");
            }
            if (token.startsWith("bearer")) {
                token = token.replace("bearer ", "");
            }
        } else {
            token = request.getParameter("token");
        }
        return token;
    }

    public static void setUser(String token, UserDTO userDTO) {
        USER_TOKEN.set(token);
        USER_INFO.set(userDTO);
    }

    public static void setTenantId(String tenantId) {
        TENANT_ID.set(tenantId);
    }

    public static void removeUser() {
        USER_TOKEN.remove();
        USER_INFO.remove();
    }

    public static UserDTO getCurrentUser() {
        return USER_INFO.get();
    }

    public static String getCurrentUserToken() {
        return "Bearer " + USER_TOKEN.get();
    }

    public static String getCurrentUserName() {
        UserDTO currentUser = getCurrentUser();
        if (currentUser != null) {
            return currentUser.getName();
        }
        return null;
    }

    public static String getCurrentTenantId() {
        UserDTO currentUser = getCurrentUser();
        if (currentUser != null) {
            AuthCenterTenant tenant = currentUser.getTenant();
            if(tenant != null){
                return tenant.getId();
            }
            return null;
        }else{
            return TENANT_ID.get();
        }
    }

    public static AuthCenterTenant getCurrentTenant() {
        UserDTO currentUser = getCurrentUser();
        if (currentUser != null) {
            return currentUser.getTenant();
        }
        return null;
    }

}
